package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanValidators;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-10-26
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {



    @Override
    public List<Category> getCategoryTree(Long parentId) {
        LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Category::getParentId,parentId);

        //带条件的查询
        List<Category> categoryList=baseMapper.selectList(lambdaQueryWrapper);

        //为categoryList中的hasChildren属性赋值
        categoryList.forEach(category -> {

            //判断是否有父Id的值是否为当前类的Id
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
            if (count>0){
                //有子类
                category.setHasChildren(true);
            }else {
                category.setHasChildren(false);
            }

        });


        return  categoryList;
    }

    @Override
    public String importCategory(List<Category> categoryList, boolean updateSupport, String operName) {
        //判决集合是否为空
        if (StringUtils.isNull(categoryList) || categoryList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Category category : categoryList)
        {
            try
            {
                //数据库中是否已经存在该分类
//                Category category1 = baseMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getName,category.getName()));
                Category category1 = baseMapper.selectById(category.getId());
                if (StringUtils.isNull(category1))
                {
                    //设置添加人的名字
                    category.setCreateBy(operName);
                    //插入分类数据
                    baseMapper.insert(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、分类 " + category.getName() + " 导入成功");
                }
                else if (updateSupport)
                {
                    //设置更新者的名字
                    category.setUpdateBy(operName);
                    //更新
                    baseMapper.updateById(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、分类 " + category.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、分类 " + category.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、分类 " + category.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<CategoryVo> getCategoryTreeList() {

        //调用自带的方法获取所有的分类信息
        List<Category> categoryList = baseMapper.selectList(null);
        //将所有的分类转换为CategoryVo类型
        List<CategoryVo> categoryVoList = categoryList.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).toList();
        //将所有的分类信息转换为分类树
        List<CategoryVo> categoryVoTree = this.getCategoryVoTree(categoryVoList);
        return categoryVoTree;

    }

    //将categoryVoList转换为分类树的方法
    private List<CategoryVo> getCategoryVoTree(List<CategoryVo> categoryVoList) {
        //创造一个返回的集合
        List<CategoryVo> categoryVoTree = new ArrayList<>();
        //遍历集合
        categoryVoList.forEach(categoryVo -> {
            //获取父id为0的分类,即一级分类
            if (categoryVo.getParentId()==0){
                //获取下一级分类信息
               categoryVo= this.addAndFindChildren(categoryVo,categoryVoList);
               categoryVoTree.add(categoryVo);
            }
        });
        return categoryVoTree ;
    }

    //获取下一级分类信息
    private CategoryVo addAndFindChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        //遍历集合
        categoryVoList.forEach(categoryVo1 -> {
            //判断categoryVo1是否为categoryVo的子分类
            if (categoryVo1.getParentId()==categoryVo.getId()){
                //获取获取下一级分类信息
                categoryVo1= this.addAndFindChildren(categoryVo1,categoryVoList);
                categoryVo.getChildren().add(categoryVo1);
            }
        });
            return categoryVo ;
    }
}
